<template>
  <div class='quantity-container'>
    <div class="content_l">
      <vxe-toolbar>
        <template #buttons>
          <vxe-button @click="$refs.xTree.setAllTreeExpand(true)">全部展开</vxe-button>
          <vxe-button @click="$refs.xTree.clearTreeExpand()">全部关闭</vxe-button>
        </template>
      </vxe-toolbar>
      <vxe-table highlight-current-row highlight-hover-row :show-header="false" show-overflow ref="xTree" border="inner" :data="depList" :tree-config="{children: 'children',transform:false,parentKey :'parentId',  line: true, iconOpen: 'el-icon-remove', iconClose: 'el-icon-circle-plus'}" class="left-table">
        <vxe-column tree-node show-overflow>
          <template #default="{ row }">
            <span>
              <!-- <img src="../../../assets/icons/png/contextMenu.gif" alt="" @click.stop="openMenu(row,$event)"> -->
              <i class="tree-node-icon fa" :class="$refs.xTree.isTreeExpandByRow(row) ? 'el-icon-folder-opened' : 'el-icon-folder'"></i>
              <span @click="clickListRow(row)" style="cursor:pointer;fontSize:12px;color:#000"> {{row.label }} </span>
            </span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div class="content_r">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <!-- 审核标识，0-未审核，1-审核通过，2-审核不通过,3-审核退回 -->
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable size="small">
            <el-option v-for="dict in identityStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="修改时间">
          <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['identify:dataReport']">导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="handleQuery"></right-toolbar>
      </el-row>
      <div class="box" ref="box">
        <el-table id="table1111" ref="quantityTable" :data="tableData" class="tableChage" border :max-height="height" style="width: 100%">
          <MyElTable v-for="(item,index) in colConfigs" :key="index" :col="item"></MyElTable>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { identifyDept } from "@/api/identity/identify";
import { dataReport } from "@/api/identity/quantityStatistics";
import MyElTable from "@/components/MyElTable";
import { deepClone } from "@/utils/index.js";

import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    return {
      //左侧部门列表
      depList: [],
      // 显示搜索条件
      showSearch: true,
      //表格头部 配置
      colConfigs: {},
      //表格数据
      tableData: [],
      // 查询参数
      queryParams: {},
      queryParamsCache: {},
      //审核状态
      identityStatusOptions: [],

      // 日期范围
      dateRange: [],
      height: 0,
    };
  },

  components: { MyElTable },

  computed: {},

  mounted() {
    console.log(" this.$refs.box: ", this.$refs.box.offsetHeight);
    this.getIdentifyDept();
    this.getDicts("iden_status").then((response) => {
      this.identityStatusOptions = response.data;
    });
  },

  methods: {
    /** 查询列表 */
    handleQuery() {
      console.log("this.dateRange: ", this.dateRange);
      // console.log(
      //   "this.addDateRange(this.queryParams, this.dateRange): ",
      //   this.addDateRange(this.queryParams, this.dateRange)
      // );
      let params = this.addDateRange(this.queryParams, this.dateRange);
      this.queryParamsCache = deepClone(params);
      console.log("this.queryParamsCache: ", this.queryParamsCache);
      dataReport(params).then((response) => {
        console.log("response: ", response);
        this.tableData = response.data.tableData;
        this.colConfigs = response.data.colConfigs;
      });
      this.height = this.$refs.box.offsetHeight;
    },
    /**获取分类列表 */
    getIdentifyDept() {
      identifyDept()
        .then((res) => {
          // let quanbu = { id: null, label: "全部", children: [] };
          // res.data.unshift(quanbu);
          this.depList = res.data;
        })
        .then(() => {
          //展开第一个节点
          this.$nextTick(() => {
            this.$refs.xTree.setCurrentRow(this.depList[0]);
            this.$refs.xTree.setTreeExpand(this.depList[0], true);
            this.clickListRow(this.depList[0]);
          });
        });
    },
    //点击左侧部门列表
    clickListRow(row) {
      console.log("row: ", row);
      this.queryParams.creCompany = row.id;
      this.queryParams.creCompanyLabel = row.label || "全部";
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = this.queryParams.creCompany;
      this.handleQuery();
    },
    handleExport() {
      let fix = document.querySelector(".el-table__fixed");
      console.log("this.queryParamsCache: ", this.queryParamsCache);
      let wb;
      let status;
      // this.queryParamsCache.status == 0
      //   ? "未审核"
      //   : this.queryParamsCache.status == 1
      //   ? "审核通过"
      //   : this.queryParamsCache.status == 3
      //   ? "审核退回"
      //   : "全部";
      switch (this.queryParamsCache.status) {
        case 0:
          status = "未审核";
          break;
        case 1:
          status = "审核通过";
          break;
        case 3:
          status = "审核退回";
          break;
        default:
          status = "全部";
      }
      let beginTime =
        this.queryParamsCache?.params?.beginTime?.replaceAll("-", "") || "time";
      let endTime =
        this.queryParamsCache?.params?.endTime?.replaceAll("-", "") || "time";
      let nowTime = new Date().toLocaleDateString();

      let fileName = `${this.queryParamsCache.creCompanyLabel}-${status}.xlsx`;
      console.log("fileName: ", fileName);
      if (fix) {
        console.log("fix: ", fix);

        //判断要导出的节点中是否有fixed的表格，如果有，转换excel时先将该dom移除，然后append回去
        document.querySelector("#table1111").removeChild(fix);
        var elt = document.getElementById("table1111");
        wb = XLSX.utils.table_to_book(elt, { raw: true });
        document.querySelector("#table1111").appendChild(fix);
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#table1111"), {
          raw: true,
        });
      }
      console.log("wb: ", wb);
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          fileName
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
  },
};
</script>

<style scoped lang='scss'>
.quantity-container {
  display: flex;
  flex-direction: row;
  .content_l {
    min-width: 240px;
    height: 100%;
    background: #fffbf0 !important;
    display: flex;
    flex-direction: column;
    .left-table {
      flex: 1;
      height: 0;
      overflow: overlay;
    }
  }
  .content_r {
    flex: 1;
    width: 0;
    margin: 0 0 0 10px;
    overflow: auto;
    padding: 10px;
    border-left: 1px solid #ccc;
    height: 100%;
    display: flex;
    flex-direction: column;
    .box {
      flex: 1;
    }
  }
}
</style>